<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="800px"
      append-to-body
      custom-class="import-dialog"
      @close="close"
    >
      <div class="form-box">
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="120px"
          class="add-form"
          :disabled="isDetail"
        >
          <div class="section">
            <div class="label">
              <label>人员信息</label>
            </div>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item
                  label="姓名"
                  prop="reserveUser"
                  :rules="[
                    {
                      required: true,
                      message: '请输入姓名',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input
                    placeholder="请输入"
                    v-model="form.reserveUser"
                    style="width: 80%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机" prop="reserveUserPhone">
                  <el-input
                    v-input.num
                    placeholder="请输入"
                    v-model="form.reserveUserPhone"
                    style="width: 80%"
                    maxlength="11"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="身份证号" prop="reservationCardNumber">
                  <el-input
                    placeholder="请输入"
                    v-model="form.reservationCardNumber"
                    style="width: 80%"
                    maxlength="18"
                  />
                </el-form-item>
              </el-col>
            </el-row> -->
          </div>
          <div class="section">
            <div class="label">
              <label>订单信息</label>
            </div>
            <el-form-item label="租住周期" prop="period">
              <el-date-picker
                v-model="form.period"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="periodChange"
                :picker-options="periodPickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="房间" prop="houseId" v-if="!isDesignatedHouse">
              <el-button
                size="small"
                type="primary"
                icon="el-icon-s-home"
                @click.stop="handleHouseSelect"
              >选择房屋
              </el-button
              >
              <el-input
                style="width: 300px; margin-left: 10px"
                v-model="form.premisesAddress"
                placeholder="请选择房屋"
                readonly
              ></el-input>
            </el-form-item>
            <!--            <el-form-item label="最晚签约日期" prop="finallySignTime">-->
            <!--              <el-date-picker-->
            <!--                v-model="form.finallySignTime"-->
            <!--                type="date"-->
            <!--                value-format="yyyy-MM-dd"-->
            <!--                placeholder="选择日期"-->
            <!--                default-time="23:59:00"-->
            <!--                @change="finallySignChange"-->
            <!--                :picker-options="pickerOptions"-->
            <!--              >-->
            <!--              </el-date-picker>-->
            <!--            </el-form-item>-->

            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="已付租金" prop="rentPaidNumber">
                  <el-input
                    v-input.num
                    placeholder="请输入"
                    v-model="form.rentPaidNumber"
                    style="width: 80%"
                    v-input.float="2"
                  >
                    <span slot="append">元/月</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已付押金" prop="depositPaidNumber">
                  <el-input
                    v-input.num
                    placeholder="请输入"
                    v-model="form.depositPaidNumber"
                    style="width: 80%"
                    v-input.float="2"
                  >
                    <span slot="append">元</span>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="押付方式" prop="payTypeId">
                  <el-select
                    v-model="form.payTypeId"
                    placeholder="请选择"
                    style="width: 80%"
                  >
                    <el-option
                      v-for="item in payTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否购买保洁费" prop="cleaningType">
                  <el-radio-group
                    v-model="form.cleaningType"
                  >
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12" v-if="form.cleaningType == 1">
                <el-form-item label="保洁费" prop="cleaningPrice">
                  <el-input
                    v-input.num
                    placeholder="请输入"
                    v-model="form.cleaningPrice"
                    style="width: 80%"
                    v-input.float="2"
                  >
                    <span slot="append">元</span>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row> -->
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
    <SelectHouse
      v-model="dialogSelectHouseVisible"
      @success="selectHouseCb"
      :orderParams="{checkInTime: form.checkInTime, checkOutTime: form.checkOutTime,orderType:'1'}"
    />
  </div>
</template>

<script>
import formRule from '@/utils/formRule.js'
import { listPayType } from '@/api/house/unmount'
import { getChargeItemList } from '@/api/contract'
import { addOrder, getOrderInfo, changeOrder } from '@/api/order/order'

// import SelectHouse from '@/views/long-short-rent/contract/list/components/select-house.vue'

import { debounce } from '@/utils'
import SelectHouse from '@/views/long-short-rent/order/component/select-house.vue'

export default {
  name: 'addOrder',
  dicts: [],
  components: {
    SelectHouse
  },
  props: {
    title: {
      default: '新建订单'
    },
    value: {
      default: false
    },
    orderId: {
      default: undefined
    },
    isDetail: {
      default: false
    },
    //是否指定房屋
    isDesignatedHouse: {
      default: false
    },
    designedHouse: {
      default: () => {
      }
    }, //指定房屋信息
    success: {
      type: Function,
      default: () => {
      }
    }
  },
  data() {
    return {
      visible: false,
      currentTab: '0',
      dialogChargeItemVisible: false,
      dialogSelectHouseVisible: false,
      //已选择房屋信息
      selectHouseObj: undefined,
      //合同列表
      contractList: [],

      //押付方式
      payTypeList: [],
      form: {},
      areaCalculateState: false,
      //收费项
      chargeItemForm: {
        chargeItemArr: []
      },
      chargeItemList: [],
      chargeItemSelected: [],
      pickerOptions: {
        disabledDate: (time) => {
          return (
            time.getTime() < new Date(this.form.checkInTime) ||
            time.getTime() > new Date(this.form.checkOutTime)
          )
        }
      },
      periodPickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < this.$moment().startOf('day').format('x')
        }
      },
      rules: {
        houseId: [{ required: true, message: '请选择房间', trigger: 'change' }],
        templateId: [
          { required: true, message: '请选择合同模板', trigger: 'blur' }
        ],
        tenantType: [
          { required: true, message: '请选择身份', trigger: 'blur' }
        ],
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人信息', trigger: 'blur' }
        ],
        socialCreditNumber: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ],
        socialCreditNumberImg: [
          {
            required: true,
            message: '请上传统一社会信用代码图',
            trigger: 'blur'
          }
        ],
        reserveUserPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          {
            validator: formRule.phone,
            message: '',
            trigger: ['change', 'blur']
          }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        reservationCardNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            validator: formRule.IDCard,
            message: '',
            trigger: ['change', 'blur']
          }
        ],

        period: [{ required: true, message: '请选择日期', trigger: 'change' }],
        contractType: [
          { required: true, message: '请选择合同类型', trigger: 'blur' }
        ],
        checkInTime: [
          { required: true, message: '请输入入住日期', trigger: 'blur' }
        ],
        checkOutTime: [
          { required: true, message: '请输入退房日期', trigger: 'blur' }
        ],
        finallySignTime: [
          { required: true, message: '请选择最晚签约日期', trigger: 'blur' }
        ],
        paymentType: [
          { required: true, message: '请选择付款方式', trigger: 'blur' }
        ],
        payTypeId: [
          { required: true, message: '请选择押付方式', trigger: 'change' }
        ],
        cleaningType: [
          {
            required: true,
            message: '请选择是否购买保洁费',
            trigger: 'change'
          }
        ],
        cleaningPrice: [
          { required: true, message: '请输入保洁费', trigger: 'blur' }
        ],
        priceAmounts: [
          { required: true, message: '请输入总金额', trigger: 'blur' }
        ],
        // depositPaidNumber: [
        //   { required: true, message: "请输入押金", trigger: "blur" },
        // ],
        // rentPaidNumber: [
        //   { required: true, message: "请输入租金", trigger: "blur" },
        // ],
        billingDate: [
          { required: true, message: '请输入号数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    customHouseName: {
      get() {
        return this.form.houseId
          ? this.form.estateName +
          this.form.buildingName +
          '栋' +
          this.form.unitName +
          '单元' +
          this.form.roomNumber
          : ''
      },
      set() {
      }
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal) {
        this.init()
      }
      this.visible = newVal // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit('input', val) // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    }
  },
  mounted() {
    this.visible = this.value
  },
  methods: {
    init() {
      //重置
      this.reset()
      //获取押付方式
      //this.getListPayType();
      this.getInfo()
      if (this.isDesignatedHouse) {
        this.$nextTick(() => {
          let houseObj = {
            houseId: '', //房屋id
            provinceId: '', //省
            provinceName: '', //省份名称
            cityId: '', //市
            cityName: '', //市名称
            districtId: '', //区
            districtName: '', //区名称
            streetId: '', //所属街道
            streetName: '', //街道名称
            communityId: '', //所属社区
            communityName: '', //所属社区名称
            premisesAddress: null, //小区地址
            roomNumber: '', //房间号
            estateId: '', //楼盘id
            estateName: '', //楼盘名称
            buildingId: '', //楼栋id
            buildingName: '', //楼栋名称
            unitId: '', //单元id
            unitName: '', //单元名称
            floors: undefined //层数
          }
          for (const key in houseObj) {
            houseObj[key] = this.designedHouse[key]
          }
          this.form = { ...this.form, ...houseObj }
        })
      }

    },
    //日期更改
    periodChange(e) {
      console.log(e)
      this.form.checkInTime = e[0] + ' 00:00:00'
      this.form.checkOutTime = e[1] + ' 23:59:00'
    },
    finallySignChange(e) {
      this.form.finallySignTime = e + ' 23:59:00'
    },
    //重置表单
    reset() {
      this.areaCalculateState = false
      this.form = {
        houseId: '', //房屋id
        provinceId: '', //省
        provinceName: '', //省份名称
        cityId: '', //市
        cityName: '', //市名称
        districtId: '', //区
        districtName: '', //区名称
        streetId: '', //所属街道
        streetName: '', //街道名称
        communityId: '', //所属社区
        communityName: '', //所属社区名称
        premisesAddress: null, //小区地址
        roomNumber: '', //房间号
        estateId: '', //楼盘id
        estateName: '', //楼盘名称
        buildingId: '', //楼栋id
        buildingName: '', //楼栋名称
        unitId: '', //单元id
        unitName: '', //单元名称
        floors: undefined, //层数
        houseArea: undefined, //房屋面积
        depositPaidNumber: undefined, //押金
        priceAmounts: undefined, //
        payTypeId: undefined, //押付方式id
        reserveUser: '', //姓名
        reserveUserPhone: '', //手机号码
        reservationCardNumber: '', //身份证号码
        houseManagerId: '', //房屋管理员id
        houseManagerName: '', //房屋管理员名字
        houseManagerPhone: '', //房屋管理员电话
        checkInTime: '', //租期开始时间
        checkOutTime: '', //租期结束时间
        paymentType: '', //付款方式：1.月租;2.日租
        finallySignTime: '', //最晚签约日期
        roomType: '', //户型
        cleaningType: '0',
        period: [],
        cleaningPrice: undefined, //保洁费
        orderSource: '1' //订单来源：1订单管理 2线上预定
      }
    },
    //获取详情
    getInfo() {
      if (!this.orderId) return
      getOrderInfo(this.orderId).then((response) => {
        let form = response.data
        form.period = [response.data.checkInTime, response.data.checkOutTime]
        this.form = form
      })
    },
    //获取押付方式
    getListPayType() {
      listPayType().then((response) => {
        this.payTypeList = response.data
      })
    },
    //移除收费项
    removeChargeItem(index) {
      this.chargeItemSelected.splice(index, 1)
    },
    //关闭收费项弹窗
    closeChargeItemDialog() {
    },
    //面积计算租金状态改变
    changeAreaCalculateState(data) {
      console.log('data', data)
      let value = data ? '1' : '0'
      this.$set(this.form, 'areaCalculateState', value)
    },
    //收费项结算类型修改
    changeSettlementType(item, index) {
      item.totalPrice = undefined
      item.unitPrice = undefined
    },
    //选择房间操作
    handleHouseSelect() {
      // 如果未选择租期
      if (!this.form.checkInTime || !this.form.checkOutTime) {
        this.$message.error('请选择租住周期')
        return
      }
      this.dialogSelectHouseVisible = true
    },
    //房间选择回调
    selectHouseCb(data) {
      this.selectHouseObj = data
      let houseObj = {
        houseId: '', //房屋id
        provinceId: '', //省
        provinceName: '', //省份名称
        cityId: '', //市
        cityName: '', //市名称
        districtId: '', //区
        districtName: '', //区名称
        streetId: '', //所属街道
        streetName: '', //街道名称
        communityId: '', //所属社区
        communityName: '', //所属社区名称
        premisesAddress: null, //小区地址
        roomNumber: '', //房间号
        estateId: '', //楼盘id
        estateName: '', //楼盘名称
        buildingId: '', //楼栋id
        buildingName: '', //楼栋名称
        unitId: '', //单元id
        unitName: '', //单元名称
        floors: undefined //层数
      }
      for (const key in houseObj) {
        houseObj[key] = data[key]
      }
      this.form = { ...this.form, ...houseObj }
    },
    //根据面积单价计算租金
    calculateRent: debounce(function() {
      if (!this.form.areaUnitPrice || !this.form.houseArea) {
        this.form.priceAmounts = undefined
        return
      }
      let value = (this.form.areaUnitPrice * this.form.houseArea).toFixed(2)
      this.form.priceAmounts = value
    }, 100),

    //移除设备
    removeFacility(item, index) {
      this.form.houseFacilitiesItemList.splice(index, 1)
    },
    //提交表单
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.cleaningType == 0) {
            delete this.form.cleaningPrice
          }
          if (this.orderId) {
            changeOrder(this.form).then((response) => {
              this.$emit('success')
              this.$message.success(response.msg || '编辑成功')
              this.visible = false
            })
          } else {
            addOrder(this.form).then((response) => {
              this.$emit('success')
              this.$message.success(response.msg || '新增成功')
              this.visible = false
            })
          }
        }
      })
    },
    //关闭
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;

  .dialog-footer {
    text-align: center;
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.form-box {
  .tabs {
    display: flex;

    .tabs-item {
      padding: 0 10px;
      height: 40px;
      line-height: 40px;
      font-size: 16px;
      position: relative;
      cursor: pointer;

      &::before {
        content: "";
        position: absolute;
        left: 50%;
        bottom: -2px;
        width: 0;
        height: 2px;
        opacity: 0;
        background: #0caaf0;
        transition: all 0.3s;
      }

      &.active {
        color: #0caaf0;

        &::before {
          opacity: 1;
          left: 0;
          width: 100%;
        }

        cursor: default;
      }
    }
  }

  .add-form {
    margin-top: 30px;

    .section {
      .label {
        display: flex;
        margin-bottom: 20px;
        font-size: 16px;
        align-items: center;
        color: #303133;

        label {
          display: block;
          width: 80px;

          &.dot::before {
            content: "*";
            color: #ff4949;
            margin-right: 4px;
          }
        }

        .icon {
          color: #02a7f0;
          font-size: 30px;
          margin-left: 30px;
          cursor: pointer;
        }
      }

      .tips {
        color: #aaaaaa;
      }

      .custom-formItem-lable {
        display: flex;
        align-items: center;

        .handle-icon {
          color: #02a7f0;
          font-size: 30px;
          margin-left: 30px;
          cursor: pointer;
        }
      }

      .handle-icon {
        color: #02a7f0;
        font-size: 30px;
        cursor: pointer;
      }
    }
  }
}
</style>
